import React, { createContext, useContext, useState, useEffect } from 'react';

type Theme = 'light' | 'dark';

interface ThemeContextType {
    theme: Theme;
    toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [theme, setTheme] = useState<Theme>('light'); // 始终使用light作为初始值
    const [mounted, setMounted] = useState(false);

    useEffect(() => {
        // 在客户端加载时从localStorage读取主题
        const savedTheme = localStorage.getItem('theme') as Theme;
        if (savedTheme) {
            setTheme(savedTheme);
        }
        setMounted(true);
    }, []);

    const toggleTheme = () => {
        setTheme((prev) => {
            const newTheme = prev === 'light' ? 'dark' : 'light';
            localStorage.setItem('theme', newTheme);
            return newTheme;
        });
    };

    // 初始加载时应用主题到body
    useEffect(() => {
        if (mounted) {
            document.body.style.backgroundColor = theme === 'light' ? '#f9f9f9' : '#343a40';
            document.body.style.color = theme === 'light' ? '#000' : '#fff';
        }
    }, [theme, mounted]);

    // 在客户端渲染完成前不显示内容，避免闪烁
    if (!mounted) {
        return null;
    }

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

export const useTheme = () => {
    const context = useContext(ThemeContext);
    if (!context) {
        throw new Error('useTheme must be used within a ThemeProvider');
    }
    return context;
}; 